import Taro from '@tarojs/taro'
import { useState, memo } from 'react';
import { connect } from 'react-redux';
import { View, Image, Button, Input } from '@tarojs/components'
import { ossUrl } from '@/utils/config'
import { setUser } from '@/actions/user'
import { updateUserName } from '@/api'
import { Dialog, Overlay } from '@/components'
import './index.scss'

const UserInfo = ({ userInfo, setUserInfo }) => {
  const [editNameFlag, setEditNameFlag] = useState(false)
  const [editIpFlag, setEditIpFlag] = useState(false)
  const [hasSelect, setHasSelect] = useState(false)
  const [hasDomestic, setHasDomestic] = useState(Taro.getStorageSync('ip') ? false : true)
  const [name, setName] = useState('')
  const [ip, setIp] = useState('')
  /** 更新用户名称 */
  const saveUserName = () => {
    if (name.trim()) {
      updateUserName(name).then(() => {
        const user = { ...userInfo, name: name }
        setUserInfo(user)
        Taro.setStorageSync('userInfo', user)
        Taro.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000
        })
        setEditNameFlag(false)
      }).catch(err => {
        console.log(err, 'err')
      })
    } else {
      Taro.showToast({
        title: '请输入名称',
        icon: 'error',
        duration: 2000
      })
    }
  }
  /** 更新 Ip 地址 */
  const updateIpAddress = () => {
    Taro.setStorageSync('ip', ip)
    setEditIpFlag(false)
    setHasSelect(false)
    setHasDomestic(false)
    Taro.showToast({ title: '设置成功', icon: 'success', duration: 2000 })
  }
  /** 取消更新 Ip 地址 */
  const clearUpdateIp = () => {
    setEditIpFlag(false)
    setIp('')
    setHasSelect(false)
  }
  /** 展示 更新 ip 地址 弹框 */
  const pretreatmentUpdateIp = () => {
    setIp('')
    setHasSelect(false)
    setEditIpFlag(true)
  }
  /** 设置 ip 为 国内用户 */
  const removeIpSelect = () => {
    setHasSelect(false)
    setHasDomestic(true)
    Taro.removeStorageSync('ip')
    Taro.showToast({ title: '设置成功', icon: 'success', duration: 2000 })
  }
  /** 退出登录 */
  const logout = () => {
    Taro.removeStorageSync('userInfo')
    Taro.showToast({
      title: '登出成功',
      icon: 'success',
      duration: 2000
    })
    setTimeout(() => {
      setUserInfo(null)
      Taro.reLaunch({ url: '/pages/home/index' })
    }, 2000)
  }
  /** render 用户输入 or 自己名称 */
  const renderInputName = () => {
    if (editNameFlag) {
      return <Input type='text' className='input bg_fff pd_l_15 pd_r_15 text_center' value={name} onInput={e => setName(e.detail.value)} onConfirm={saveUserName} placeholder='输入真实姓名，让老师更好发现你哟' placeholderClass='placeholder' />
    }
    return <View className='size_32 text_center'>{userInfo && userInfo.name}</View>
  }
  /** render 选择 ip 的弹框 */
  const renderSelectDialog = () => {
    if (hasSelect) {
      return (
        <View className='select_wrapper mg_0_auto'>
          <Overlay close={() => setHasSelect(false)}></Overlay>
          <View className='center_wrapper fixed bottom_0 height_auto pd_b_20'>
            <View className='card bg_fff width_fill text_center cor_333 size_32' style={{ borderTopLeftRadius: '16px', borderTopRightRadius: '16px', borderBottom: '1rpx solid #dadada' }} onClick={removeIpSelect}>中国大陆</View>
            <View className='card bg_fff width_fill flex flex_j_center flex_column' style={{ borderBottomLeftRadius: '16px', borderBottomRightRadius: '16px' }} onClick={pretreatmentUpdateIp}>
              <View className='size_32 text_center cor_333'>港澳台及海外用户</View>
              <View className='size_18 cor_333 text_center mg_t_10'>（请先询问老师 获得海外访问链接哦）</View>
            </View>
            <View className='clear card bg_fff width_fill text_center size_700 size_32 radius_32 mg_t_14'>取消</View>
          </View>
        </View>
      )
    }

  }
  /** 渲染 更新 ip 的 dom */
  const renderUpdateIpDialog = () => {
    return (
      <Dialog show={editIpFlag} close={() => setEditIpFlag(false)} customClass='update_dialog text_center'>
        <View className='cor_333 size_32'>请输入港澳台及海外用户访问链接：</View>
        <View className='cor_333 size_20 mg_t_20'>（请先询问老师 获得海外访问链接哦）</View>
        <Input className='input radius_20' value={ip} onInput={e => setIp(e.detail.value)} placeholder='https://www.hk.emotechlab.com' />
        <View className='btn_wrapper flex mg_0_auto'>
          <Button className='btn cor_main bg_fff flex_center size_28 mg_none flex_1' onClick={clearUpdateIp}>取消</Button>
          <Button className='btn cor_fff bg_main flex_center size_28 mg_none flex_1' onClick={updateIpAddress}>确定</Button>
        </View>
      </Dialog>
    )
  }
  return (
    <View className='userInfo pd_t_40 relative height_full ov_hidden'>
      <View className='flex_center'>
        <Image src={userInfo && userInfo.avatar} className='avatar radius_oval'></Image>
      </View>
      <View className='card bg_fff pd_l_50 mg_t_46 pd_r_50 width_fill grid'>
        <View className='key size_700 size_32'>姓名</View>
        {renderInputName()}
        <Image src={ossUrl + '/pencil.png'} className='edit' onClick={() => setEditNameFlag(true)}></Image>
      </View>
      <View className='card bg_fff pd_l_50 mg_t_46 pd_r_50 width_fill grid'>
        <View className='key size_700 size_32'>用户ID</View>
        <View className='size_32 text_center'>{userInfo && userInfo.uid}</View>
        <View className='edit'></View>
      </View>
      <View className='card bg_fff pd_l_50 mg_t_46 pd_r_50 width_fill grid' onClick={() => setHasSelect(true)}>
        <View className='key size_700 size_32'>地区</View>
        <View className='size_32 text_center'>{hasDomestic ? '中国大陆' : '海外用户'}</View>
        <Image className='arrow' src={ossUrl + '/rightArrow.png'}></Image>
      </View>
      <View className='card bg_fff pd_l_50 mg_t_46 pd_r_50 width_fill grid' onClick={() => Taro.navigateTo({ url: '/pages/feedback/index' })}>
        <View className='key size_700 size_32'>常见问题</View>
        <View className='size_32 text_center'></View>
        <Image className='arrow' src={ossUrl + '/rightArrow.png'}></Image>
      </View>

      <Button className='logout absolute left_0 right_0 radius_16 flex_center bg_fff size_32' onClick={logout}>退出登陆</Button>

      {renderSelectDialog()}
      {renderUpdateIpDialog()}
    </View>
  )
}
const mapStateToProps = ({ user }) => ({
  userInfo: user.userInfo
});
const mapDispatchToProps = dispatch => ({
  setUserInfo(userInfo) {
    dispatch(setUser(userInfo))
  }
})
export default connect(mapStateToProps, mapDispatchToProps)(memo(UserInfo))
